import time
import logging

from django.http import HttpResponse
import traceback

from sentry_sdk import capture_exception, capture_message
from . import dingtalk

logger = logging.getLogger(__name__)


def performance_logger_middleware(get_response):
    def middleware(request):
        start_time = time.time()
        response = get_response(request)
        duration = time.time() - start_time
        response["X-Page-Duration-ms"] = int(duration * 1000)
        logger.info('%s %s %s', duration, request.path, request.GET.dict())
        if duration > 300:
            capture_message("slow request for url: %s with duration: %s", (request.build_absolute_uri(), duration))
        return response
    return middleware


class PerformanceAndExceptionLoggerMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
    
    def __call__(self, request):
        start_time = time.time()
        response = self.get_response(request)
        duration = time.time() - start_time
        response["X-Page-Duration-ms"] = int(duration * 1000)
        logger.info('duration: %s url:%s parameters:%s', duration, request.path, request.GET.dict())
        return response
    
    def process_exception(self, request, exception):
        # 如果出现异常
        if exception:
            # 构造异常消息
            message = "url: {url} ** msg: {error}````{tb}````".format(
                # 请求的url
                url=request.build_absolute_uri(),
                # 异常的详细信息
                error=repr(exception),
                # 堆栈信息
                tb=traceback.format_exc(),
            )
            # 记录warning日志
            logger.warning(message)
            # 发一个钉钉消息
            dingtalk.send(message)
            # 上报sentry服务
            capture_exception(exception)

        return HttpResponse("Error processing the request, please contact the system administrator", status=500)